"use client";

import { useState, useEffect, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Settings, Monitor, Type, Save, Loader2 } from "lucide-react";
import { type API } from "@/lib/api";

interface TerminalConfigProps {
  channelId: string | null;
  terminalId: string;
  currentNickname?: string;
  api: API | null;
  currentAlias?: string;
  onConfigUpdate: (config: {
    nickname?: string;
    alias?: string;
    fontFamily?: string;
    fontSize?: number;
  }) => void;
}

export default function TerminalConfig({ channelId, terminalId, currentNickname = "", currentAlias = "", api, onConfigUpdate }: TerminalConfigProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [nickname, setNickname] = useState(currentNickname);
  const [alias, setAlias] = useState(currentAlias);
  const [fontFamily, setFontFamily] = useState("Fira Code VF");
  const [fontSize, setFontSize] = useState(12);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Reset form when opened
  useEffect(() => {
    if (isOpen) {
      setNickname(currentNickname);
      setAlias(currentAlias);
      setError(null);
    }
  }, [isOpen, currentNickname, currentAlias]);

  // Listen for real-time alias updates from other peers
  useEffect(() => {
    if (!api || !channelId) return;

    const unsubscribe = api.subscribeToTerminalRename(channelId, (renameEvent) => {
      if (renameEvent.sessionId === terminalId) {
        // Update local state when this terminal is renamed by another peer
        setAlias(renameEvent.newName || "");
        // Notify parent component of the change
        onConfigUpdate({
          alias: renameEvent.newName,
        });
      }
    });

    return () => {
      if (unsubscribe) unsubscribe();
    };
  }, [api, channelId, terminalId, onConfigUpdate]);

  const handleSave = async () => {
    if (!api) {
      setError("API not available");
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      // Check if alias has changed
      if (alias !== currentAlias) {
        console.log('📡 Renaming terminal:', channelId, terminalId, alias);
        await api.renameTerminal(channelId, terminalId, alias || undefined);
      }

      // Update local config for other settings
      onConfigUpdate({
        nickname: nickname || undefined,
        alias: alias || undefined,
        fontFamily,
        fontSize
      });

      setIsOpen(false);
    } catch (err) {
      console.error("Failed to rename terminal:", err);
      setError("Failed to update terminal alias");
    } finally {
      setIsLoading(false);
    }
  };

  const fontOptions = [
    { value: "Fira Code VF", label: "Fira Code VF" },
    { value: "ui-monospace", label: "UI Monospace" },
    { value: "SFMono-Regular", label: "SF Mono" },
    { value: "Menlo", label: "Menlo" },
    { value: "Monaco", label: "Monaco" },
    { value: "Consolas", label: "Consolas" },
    { value: "'Liberation Mono'", label: "Liberation Mono" },
    { value: "'Courier New'", label: "Courier New" },
    { value: "monospace", label: "Monospace" }
  ];

  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogTrigger asChild>
        <Button size="sm" variant="outline" className="h-8 w-8 p-0">
          <Settings className="h-4 w-4" />
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Monitor className="h-5 w-5" />
            终端配置
          </DialogTitle>
          <DialogDescription>
            配置终端 {terminalId} 的显示和个性化设置
          </DialogDescription>

          {error && (
            <div className="bg-red-50 border border-red-200 rounded-md p-3">
              <p className="text-sm text-red-600">{error}</p>
            </div>
          )}
        </DialogHeader>

        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <Label htmlFor="nickname" className="flex items-center gap-2">
              <Type className="h-4 w-4" />
              用户昵称
            </Label>
            <Input
              id="nickname"
              value={nickname}
              onChange={(e) => setNickname(e.target.value)}
              placeholder="设置您的昵称"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="alias" className="flex items-center justify-between">
              <span>终端别名</span>
              <span className="text-xs text-gray-500">实时同步</span>
            </Label>
            <Input
              id="alias"
              value={alias}
              onChange={(e) => setAlias(e.target.value)}
              placeholder="为此终端设置别名"
            />
            <p className="text-xs text-gray-500">
              设置的别名将在所有连接的设备间实时同步
            </p>
          </div>

          <div className="space-y-2">
            <Label htmlFor="fontFamily">字体</Label>
            <Select value={fontFamily} onValueChange={setFontFamily}>
              <SelectTrigger>
                <SelectValue placeholder="选择字体" />
              </SelectTrigger>
              <SelectContent>
                {fontOptions.map((font) => (
                  <SelectItem key={font.value} value={font.value}>
                    {font.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="fontSize">字体大小</Label>
            <Select value={fontSize.toString()} onValueChange={(value) => setFontSize(parseInt(value))}>
              <SelectTrigger>
                <SelectValue placeholder="选择字体大小" />
              </SelectTrigger>
              <SelectContent>
                {[10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24].map((size) => (
                  <SelectItem key={size} value={size.toString()}>
                    {size}px
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        <DialogFooter>
          <Button type="button" variant="outline" onClick={() => setIsOpen(false)}>
            取消
          </Button>
          <Button type="button" onClick={handleSave} disabled={isLoading} className="flex items-center gap-2">
            {isLoading ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <Save className="h-4 w-4" />
            )}
            {isLoading ? "保存中..." : "保存配置"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
